//
//  SearchPreOrderViewController.m
//  xingfugangwan
//
//  Created by rainday on 14/12/28.
//  Copyright (c) 2014年 rainday. All rights reserved.
//

#import "SearchPreOrderViewController.h"
#import <ReactiveCocoa.h>
#import <RACEXTScope.h>
#import <AFNetworking.h>
#import <MBProgressHUD.h>
#import "NetIP.h"

@interface SearchPreOrderViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic ,weak) IBOutlet UITableView *tableView;
@property (nonatomic ,weak) IBOutlet UITextField *textField;
@property (nonatomic ,strong) NSMutableArray *dataArray;
@property (nonatomic ,strong) NSString *lastName;

- (IBAction)dismissVC:(id)sender;
@end

static NSString *reuseIdentify = @"Cell";


@implementation SearchPreOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _dataArray = [NSMutableArray array];
    
    @weakify(self);
    
    [[[_textField rac_textSignal] filter:^BOOL(NSString *value) {
        BOOL isCH = YES;
        NSInteger len = value.length;
        if (len<2) {
            return NO;
        }
        
        for (int i=0; i<len; i++) {
            
            NSString *temp = [value substringWithRange:NSMakeRange(i,1)];
            const char *u8Temp = [temp UTF8String];
            if (3 !=strlen(u8Temp)) {
                isCH = NO;
                break;
            }
            
        }
        
        return isCH;
        
    }]subscribeNext:^(NSString *name) {
       
        if ([self.lastName isEqualToString:name]) return ;
        self.lastName = name;
        @strongify(self);
        [self performSelectorInBackground:@selector(downData:) withObject:name];
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentify];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentify];
    }
    
    if (indexPath.row< [_dataArray count]) {
        
        NSDictionary *dic = (NSDictionary *)([_dataArray objectAtIndex:indexPath.row]);
      

        
        cell.textLabel.text = [NSString stringWithFormat:@"订单号:%@      联系人:%@      负责人:%@",[dic objectForKey:@"orderID"],[dic objectForKey:@"联系人"],[dic objectForKey:@"负责人"]];
        
    }
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_delegate respondsToSelector:@selector(hasSelectedOreder:)]) {
        NSDictionary *dic = (NSDictionary *)([_dataArray objectAtIndex:indexPath.row]);
        [_delegate hasSelectedOreder:[dic objectForKey:@"orderID"]];
        _lastName = @"";
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
}


- (void)downData:(NSString *)name
{
    __weak NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    id __weak token = [userDefaults objectForKey:@"token"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",token] forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"已预约",@"status",name ,@"name", @"1",@"current_page",@"20",@"num_per_page",nil];
    
    @weakify(self)
    [manager POST:[[NetIP shareNetAddress] getSearchOrderURLString] parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        @strongify(self)
        NSLog(@"%@",responseObject);
        NSDictionary *dic = responseObject;
        if ([[dic objectForKey:@"state"] isEqualToString:@"success"]) {
            [self performSelectorOnMainThread:@selector(setDataArray:) withObject:[NSMutableArray arrayWithArray:[dic objectForKey:@"订单"]] waitUntilDone:YES];
            return ;
        }
        
        
        
        [self performSelectorOnMainThread:@selector(showHUD:) withObject:[dic objectForKey:@"message"] waitUntilDone:YES];
        
        
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    

}


- (void)setDataArray:(NSMutableArray *)dataArray
{
    
    _dataArray = dataArray;
    [_tableView reloadData];
    
}

- (void)showHUD:(NSString *)message
{
    
    [_dataArray removeAllObjects];
    [_tableView reloadData];
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    
    HUD.labelText = message;
    [self.view addSubview:HUD];
    [HUD showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    }];
    
}


- (void)dismissVC:(id)sender
{
    _lastName = @"";
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
